/* TDP SmartRepair PAC3 */

package edu.uoc.tdp.pac3.client;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;



import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import java.awt.Font;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Locale;



import edu.uoc.tdp.pac3.common.GestorPreusInterface;
import edu.uoc.tdp.pac3.common.TDSLanguageUtils;
import edu.uoc.tdp.pac3.common.SmartRepairException;

public class Client_v2 extends JFrame {


	private GestorPreusInterface objecteRemot;
	
	private JPanel contentPane;
	private JPanel jPanel1;
	private JPanel panelPressupost;
	private JPanel panelConsulta;
	
	private JLabel etiInicial;
	
	private JMenuBar menuBar;
	private JMenu mnInici;
	private JMenuItem mntmConnectaServidor;
	private JMenuItem mntmSortir;
	private JMenu mnOpcions;
	private JMenuItem mntmConsultaPreus;
	private JMenuItem mntmCalculPressupostos;
	 
	private final String URL = "localhost";
	private final int PORT = 1099;
	private final String JNDI_NAME = "PAC3";


	/////private boolean CONNECTAT = false;
	
	private static final long serialVersionUID = 1L;

	private final String NL = System.getProperty("line.separator");

	



	/**
	 * Create the frame.
	 */
	public Client_v2() {

		objecteRemot = null;
		
		initComponents();
		panelPressupost = jPanel1;
		panelConsulta = jPanel1;
		
		setLocation(650, 15);
	}
	
	
	protected void mntmCalculPressupostosActionPerformed(ActionEvent evt) {
		// TODO Auto-generated method stub

		if (objecteRemot == null){
			JOptionPane.showMessageDialog(getContentPane(),
					TDSLanguageUtils.getMessage("ERR_NO_CONN"),
					"SmartRepair", JOptionPane.INFORMATION_MESSAGE);				
		}
		else{

			//System.out.println("-----ara netaja la finestra --------------");
			netejaFinestra();
			
			try{
				
				panelPressupost = new PanelPressupost(objecteRemot);
				this.add(panelPressupost);
				this.pack(); // imppppppppppppppprtant
				
                
    		//	List<ConsultaPreus> llista = objecteRemot.consultaPreus(1);
    			//for(ConsultaPreus p:llista){
    				//System.out.println(p.toString());
    			//}


			}
			catch(RemoteException e){
				/////////////////////////////////////////////////////////////////////////////////////////////
			}
			catch(Exception e){
				System.err.println(e);
				e.printStackTrace();
				JOptionPane.showMessageDialog(getContentPane(),
						TDSLanguageUtils.getMessage("ERR_EXCEPTION")+ NL +
						e.getMessage(), "SmartRepair", JOptionPane.ERROR_MESSAGE);
			}
		}
		
	}

	
	
	
	protected void mntmConsultaPreusActionPerformed(ActionEvent evt) {
		// TODO Auto-generated method stub

		
		if (objecteRemot == null){
			JOptionPane.showMessageDialog(getContentPane(),
					TDSLanguageUtils.getMessage("ERR_NO_CONN"),
					"SmartRepair", JOptionPane.INFORMATION_MESSAGE);				
		}
		else{
			System.out.println("-----ara netaja la finestra --------------");
			netejaFinestra();

			try{
				
				panelConsulta = new PanelConsulta(objecteRemot);
				this.add(panelConsulta);
				this.pack();

			}
			catch(RemoteException e){
				/////////////////////////////////////////////////////////////////////////
			}
			catch(Exception e){
				System.err.println(e);
				e.printStackTrace();
				JOptionPane.showMessageDialog(getContentPane(),
						TDSLanguageUtils.getMessage("ERR_EXCEPTION")+ NL +
						e.getMessage(), "SmartRepair", JOptionPane.ERROR_MESSAGE);
			}
		}
		
		
	}

	
	
	private void netejaFinestra() {
		
		this.remove(jPanel1);
		this.remove(panelPressupost);
		this.remove(panelConsulta);
	}

	
	protected void mntmConnectaServidorActionPerformed(ActionEvent evt) {
		// TODO Auto-generated method stub
		
		try{
			System.out.println("Connectant al servidor des del client...");
			Registry registry = LocateRegistry.getRegistry(URL, PORT);
			objecteRemot = (GestorPreusInterface)registry.lookup(JNDI_NAME);
			System.out.println("Connectats!");
			
			JOptionPane.showMessageDialog(getContentPane(),
									TDSLanguageUtils.getMessage("CONN_OK"),
									"SmartRepair", JOptionPane.INFORMATION_MESSAGE);
		}
		catch (NotBoundException e){
			JOptionPane.showMessageDialog(getContentPane(),
					TDSLanguageUtils.getMessage("ERR_NOT_BOUND")+ NL +
					e.getMessage(), "SmartRepair", JOptionPane.ERROR_MESSAGE);
		}
		catch (RemoteException e){
			JOptionPane.showMessageDialog(getContentPane(),
					TDSLanguageUtils.getMessage("ERR_REMOT")+ NL +
					e.getMessage(), "SmartRepair", JOptionPane.ERROR_MESSAGE);
		}
		catch (Exception e){
			JOptionPane.showMessageDialog(getContentPane(),
					TDSLanguageUtils.getMessage("ERR_EXCEPTION")+ NL +
					e.getMessage(), "SmartRepair", JOptionPane.ERROR_MESSAGE);
		}

		
	}

	
	
	
	
	
	

	private void initComponents() {
		// TODO Auto-generated method stub
		
		setTitle(TDSLanguageUtils.getMessage("titol.finestra"));

		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 506, 347);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		
		jPanel1 = new JPanel();
		contentPane.add(jPanel1, BorderLayout.CENTER);
		

		etiInicial = new JLabel("");
		etiInicial.setText(TDSLanguageUtils.getMessage("client.missatge"));		
		etiInicial.setFont(new Font("Tahoma", Font.BOLD, 14));
		etiInicial.setHorizontalAlignment(SwingConstants.CENTER);



		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		//					CREA ELS ITEMS DEL MENU
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		
		// crea la barra de menu -----------------------------------------
		menuBar = new javax.swing.JMenuBar();
		setJMenuBar(menuBar);
		
		// crea i afegeix el menu 'inici' ------------------------------------
		mnInici = new javax.swing.JMenu(TDSLanguageUtils.getMessage("menu.inici"));
		menuBar.add(mnInici);

		
		// afegeix al menu 'inici' l'opcio 'connecta servidor' --------------------------------------
		mntmConnectaServidor = new javax.swing.JMenuItem(TDSLanguageUtils.getMessage("menu.connectar"));
		mnInici.add(mntmConnectaServidor);
		// i crea el listener
		mntmConnectaServidor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	mntmConnectaServidorActionPerformed(evt);
            }
        });		
		

		// afegeix al menu 'inici' l'opcio 'sortir' ------------------------------------
		mntmSortir = new javax.swing.JMenuItem(TDSLanguageUtils.getMessage("menu.sortir"));
		mnInici.add(mntmSortir);
		// i crea el listener
		mntmSortir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	mntmSortirActionPerformed(evt);
            }
        });

		
		// crea i afegeix el menu 'opcions' -----------------------------------
		mnOpcions = new javax.swing.JMenu(TDSLanguageUtils.getMessage("menu.opcions"));
		menuBar.add(mnOpcions);

		
		// afegeix al menu 'opcions' l'opcio 'consulta preus' ----------------------------
		mntmConsultaPreus = new javax.swing.JMenuItem(TDSLanguageUtils.getMessage("menu.consulta"));
		mnOpcions.add(mntmConsultaPreus);
		// i crea el listener
		mntmConsultaPreus.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	mntmConsultaPreusActionPerformed(evt);
            }
        });

		
		// afegeix al menu 'opcions' l'opcio 'calcular pressupostos' ----------------------------		
		mntmCalculPressupostos = new javax.swing.JMenuItem(TDSLanguageUtils.getMessage("menu.calcul"));
		mnOpcions.add(mntmCalculPressupostos);
		// i afegeix el listener
		mntmCalculPressupostos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	mntmCalculPressupostosActionPerformed(evt);
            }
        });
		
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

		
		GroupLayout gl_jPanel1 = new GroupLayout(jPanel1);
		gl_jPanel1.setHorizontalGroup(
			gl_jPanel1.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_jPanel1.createSequentialGroup()
					.addGap(90)
					.addComponent(etiInicial, GroupLayout.PREFERRED_SIZE, 301, GroupLayout.PREFERRED_SIZE)
					.addContainerGap(89, Short.MAX_VALUE))
		);
		gl_jPanel1.setVerticalGroup(
			gl_jPanel1.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_jPanel1.createSequentialGroup()
					.addGap(132)
					.addComponent(etiInicial)
					.addContainerGap(131, Short.MAX_VALUE))
		);
		jPanel1.setLayout(gl_jPanel1);
		
	}



	protected void mntmSortirActionPerformed(ActionEvent evt) {
		// TODO Auto-generated method stub
		dispose();
		System.exit(0);
	}

	
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		
		if(args.length==0){
			TDSLanguageUtils.setDefaultLanguage("i18n/messages_ca_ES");
		}
		if(args.length==1) {
			Locale locale = new Locale(args[0]);
			TDSLanguageUtils.setLanguage("i18n/messages", locale);			
		}

		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Client_v2 frame = new Client_v2();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	
}
